//
//  YSGMyopiaRecordListController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/1/5.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit

/// 挂号记录
class YSGMyopiaRecordListController: BaseViewController {
    
    private var current: Int = 1
    
    private var viewModel: YSGMyopiaRecordViewModel?

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "检查记录"
        setupRefresh()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.separatorStyle = .none
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.estimatedRowHeight = 190
            tableView.rowHeight = UITableView.automaticDimension
            
            tableView.register(YSGMyopiaRecordListCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaRecordListCell.reuseIdentifier())
        }
    }
}

extension YSGMyopiaRecordListController {
    private func setupRefresh() {
        tableView.mj_header = refreshHeader(action: #selector(loadNewData))
        tableView.mj_footer = refreshFooter(action: #selector(loadMoreData))
        tableView.mj_header?.beginRefreshing()
    }
    
    private func endRefresh() {
        tableView.mj_header?.endRefreshing()
        tableView.mj_footer?.endRefreshing()
    }
    
    @objc private func loadNewData() {
        current = 1
        loadData(loadMore: false)
    }
    
    @objc private func loadMoreData() {
        current += 1
        loadData(loadMore: true)
    }
    
    private func loadData(loadMore: Bool) {
        YSGMyopiaRecordViewModel.getMyopiaRecordList(current: current) { (models, message, code) in
            self.endRefresh()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
                self.current = loadMore ? self.current - 1 : 1
            case .success:
                guard let models = models else {
                    self.current = loadMore ? self.current - 1 : 1
                    return
                }
                
                if !loadMore {
                    self.viewModel = YSGMyopiaRecordViewModel(models: models)
                } else {
                    self.viewModel?.loadMore(with: models)
                }
                self.tableView.reloadData()
                
                self.current = loadMore ? (models.isEmpty ? self.current - 1 : self.current) : 1
            }
        }
    }
    
    @objc private func loginSuccess() {
        tableView.mj_header?.beginRefreshing()
    }
}

extension YSGMyopiaRecordListController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRow ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaRecordListCell.reuseIdentifier(),
                                                 for: indexPath) as! YSGMyopiaRecordListCell
        cell.delegate = self
        if let vm = viewModel?.viewModel(at: indexPath) {
            cell.configure(with: vm)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(at: indexPath) else { return }
        
        pushRecordVc(recordId: vm.model.checkFormDetailId ?? "")
    }
}

extension YSGMyopiaRecordListController: YSGMyopiaRecordListCellDelegate {
    func cancelReserve(cell: YSGMyopiaRecordListCell) {
        guard let indexPath = tableView.indexPath(for: cell),
              let vm = viewModel?.viewModel(at: indexPath) else { return }
        
        HUDTool.showActivity()
        YSGMyopiaRecordViewModel.cancelMyopiaReserve(recordId: vm.model.checkFormDetailId ?? "") { (message, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
            case .success:
                self.loadData(loadMore: false)
            }
        }
    }
}

extension YSGMyopiaRecordListController {
    private func pushRecordVc(recordId: String) {
        let recordVc = YSGMyopiaRecordController(recordId: recordId)
        navigationController?.pushViewController(recordVc, animated: true)
    }
}
